package io.github.mymonstercat.utils;

import io.github.mymonstercat.entity.VerificationVo;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

public class Verification {

    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList("image/jpeg", "image/png", "image/gif");
    private static final long MAX_FILE_SIZE = 20 * 1024 * 1024; // 20 MB

    private static final String PDF = "application/pdf";

    public static VerificationVo validateFile(MultipartFile file) {

        if (file == null) {
            return new VerificationVo(0, "文件为空。", null);
        }

        try {
            String fileType = file.getContentType();
            if (fileType == null) {
                return new VerificationVo(0, "无法确定文件类型。", null);
            }
            if (validateFileTypeToPdf(fileType)) {
                return new VerificationVo(2, "", null);
            }
            if (!validateFileType(fileType)) {
                return new VerificationVo(0, "文件类型为非图片。", fileType);
            }
        } catch (Exception e) {
            return new VerificationVo(0, "无法确定文件类型。", null);
        }

        if (!validateFileSize(file)) {
            return new VerificationVo(0, "文件大小超过最大限制。", null);
        }

        return new VerificationVo(1, "图片合规", null);
    }

    private static boolean validateFileType(String fileType) {
        return ALLOWED_IMAGE_TYPES.contains(fileType);
    }

    private static boolean validateFileTypeToPdf(String fileType) {
        return PDF.contains(fileType);
    }

    private static boolean validateFileSize(MultipartFile file) {
        return file.getSize() <= MAX_FILE_SIZE;
    }

//    public static void main(String[] args) throws IOException {
//        File file = new File("E:/projects_new/guanwang/resources/images/page_1_img_1.png");
//
//        FileInputStream input = new FileInputStream(file);
//        MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "image/png", input);
//        VerificationVo result = validateFile(multipartFile);
//
//        System.out.println(result);
//    }
}
